const koa = require("koa");
const views = require("koa-views");
const static = require("koa-static");
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");
const md5 = require("md5");
const musicData = require("./data/music.json");
const app = new koa();
const router = new Router();
app.use(views(__dirname + "/views"), {
    map: {
        html: "pug"
    }
})
app.use(static(__dirname + "/static"));
app.use(bodyParser());
//登录页面，md5验证cookie，通过则到list页面，否则还是login页面
router.get("/login", async (ctx, next) => {
    let cookieInfo = ctx.cookies.get("isLogin")
    if (cookieInfo) {
        let serverInfo = md5("张三" + "123");
        if (serverInfo == cookieInfo) {
            ctx.redirect("/list");
        }
    }
    await ctx.render("login.pug");
})

//login页面中form表单提交 username,pwd,memberMe
//根据memberMe判断是否用md5设置cookie，通过重定向到/list 否则到/error页面，之后再到/login页面
router.post("/checkUser", (ctx, next) => {
    //假定用户名是张三 密码是123；
    if (ctx.request.body.username == "张三" && ctx.request.body.pwd == "123") {
        console.log(ctx.request.body);//ctx.request.body存储post提交的数据
        //需要cookie储存登录成功的状态；有效期7天
        if (ctx.request.body.memberMe) {
            let loginStatus = md5("张三" + "123");
            ctx.cookies.set("isLogin", loginStatus, {
                maxAge: 3600 * 1000 * 24 * 7
            })
        }
        //跳转到list页面；
        ctx.redirect("/list");
    } else {
        //用户名或者密码错误，跳转到错误页面；
        ctx.redirect("/error");
    }
})
router.get("/list", async (ctx, next) => {
    await ctx.render("list.pug", {
        musicData
    });
})
router.get("/error", async (ctx, next) => {
    await ctx.render("error.pug");
})
//音乐详细页面
router.get("/detail",async (ctx,next)=>{
    await ctx.render("detail.pug");
})

app.use(router.routes());
app.listen(3000);